package com.shen.JUC.LockTest;

public class Produced {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.down();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.down();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}

//1.判断等待  2.业务  3.通知
class Data {
    private int num = 0;

    //+1
    public synchronized void add() throws InterruptedException {
        while (num != 0) {
            //等待操作
            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName()+num);
        //通知消费
        this.notifyAll();

    }

    //-1
    public synchronized void down() throws InterruptedException {
        while (num == 0) {
            //等待操作
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName()+num);
        //通知生产
        this.notifyAll();
    }
}